package rpc

import (
	"common/config"
	"common/discover"
	"common/logs"
	"context"
	"fmt"
	"user/pb"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/resolver"
)

var UserRpcClient pb.UserServiceClient

func Init() {
	userDomain := config.Conf.Domain["user"]
	logs.Info("%v", config.Conf.Etcd)
	r := discover.NewResolver(config.Conf.Etcd)
	resolver.Register(r)
	initClient(userDomain.Name, userDomain.LoadBalance, &UserRpcClient)
}

func initClient(name string, loadBalnce bool, client interface{}) {
	addr := fmt.Sprintf("etcd://%s", name)
	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	}
	if loadBalnce {
		// 设置负载均衡策略。默认是轮询
		opts = append(opts, grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, "round_robin")))
	}
	conn, err := grpc.DialContext(context.TODO(), addr, opts...)
	if err != nil {
		logs.Error("init client err : %v", err)
	}
	switch c := client.(type) {
	case *pb.UserServiceClient:
		*c = pb.NewUserServiceClient(conn)
	default:
		logs.Fatal("unsupported client type")

	}

}
